﻿// (c) Copyright Fernando Cerqueira.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using Microsoft.VisualStudio.Shell;
using AppRes = WindowsPhoneCommands.Resources;
using System.Resources;
using System.Collections;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using EnvDTE;

// ReSharper disable CheckNamespace
namespace WindowsPhoneCommands
// ReSharper restore CheckNamespace
{
    /// <summary>
    /// Interaction logic for PhoneTranslateResx.xaml
    /// </summary>
    // ReSharper disable RedundantExtendsListEntry
    public partial class PhoneTranslateResx : UserControl
    // ReSharper restore RedundantExtendsListEntry
    {
        private bool _loaded;
        private readonly ToolWindowPane _parentWindow;
        private string _projectName;
        private string _rootProject;
        private int _qtdKeyOrph;
        private int _qtdTargetNOk;
        private string[] _filesLangResources;
        private List<KeyValuePair<string, string>> _headerLngs;
        private BackgroundWorker _workerTranlate;
        private string _newKeyResx;
        private string _newCommentResx;

        public PhoneTranslateResx()
        {
            InitializeComponent();
        }

        private WindowsPhoneCommandsPackage Package
        {
            get { return (WindowsPhoneCommandsPackage)_parentWindow.Package; }
        }

        public PhoneTranslateResx(ToolWindowPane parentWindow)
        {
            _parentWindow = parentWindow;

            InitializeComponent();

            Loaded += PhoneTranslateResxLoaded;

        }

        private void PhoneTranslateResxLoaded(object sender, RoutedEventArgs e)
        {
            if (!_loaded)
            {
                Waitresx.Visibility = Visibility.Visible;
                Background = VsTheming.GetDialogBackground();
                Foreground = VsTheming.GetWindowText();

                DGResx.Background = VsTheming.GetDialogBackground();
                DGResx.Foreground = VsTheming.GetWindowText();
                ChkSync.Foreground = VsTheming.GetColorError();
                QtdOrph.Foreground = VsTheming.GetColorError();
                titkeyorph.Foreground = VsTheming.GetColorError();
                BntTargetFolder.Visibility = Visibility.Hidden;

                Dispatcher.BeginInvoke(new Action(LoadBackground), DispatcherPriority.Background,
                                       null);
            }
        }

        private void LoadBackground()
        {
            var toolwin = (WpcTranslteToolWindow)_parentWindow;
            _projectName = toolwin.OwnerProject;
            _parentWindow.Caption = WindowsPhoneCommands.Resources.TitleTranslateResx + " (" + _projectName + ")";

            switch (UserSettings.Current.EngineTranslate)
            {
                case EngineTranslate.Google:
                    Engine.Source = new BitmapImage(new Uri(Constants.RootResource + Constants.GoogleLogo, UriKind.RelativeOrAbsolute));
                    break;
                case EngineTranslate.Bing:
                    Engine.Source = new BitmapImage(new Uri(Constants.RootResource + Constants.BingLogo, UriKind.RelativeOrAbsolute));
                    break;
                default:
                    Engine.Visibility = Visibility.Collapsed;
                    break;
            }

            var seletedProject = EnvPhoneDevice.FindProjectByName(Package.EnvDte, _projectName);
            var directoryInfo = new FileInfo(seletedProject.FullName).Directory;
            if (directoryInfo != null)
            {
                _rootProject = directoryInfo.FullName + "\\";
            }

            DGResx.Width = GrdMain.ActualWidth - 30;
            GrdCmd.Width = GrdMain.ActualWidth - 30;

            CboPrjLng.ItemsSource = EnvPhoneDevice.PhoneLanguageSupport().Values.ToArray();
            CboPrjLng.SelectedItem = EnvPhoneDevice.GetValuePhoneLanguageSupport(toolwin.NeutralResource);
            if (CboPrjLng.SelectedItem != null)
            {
                CboPrjLng.IsEnabled = false;
                var res = EnvPhoneDevice.GetListNeutralResourcesFromProject(seletedProject);
                CboFilesResx.ItemsSource = res;
                CboFilesResx.SelectedItem = null;
                if (CboFilesResx.Items.Count == 1)
                {
                    CboFilesResx.SelectedIndex = 0;
                }
                if (CboFilesResx.Items.Count > 1)
                {
                    if (toolwin.SelectedResource != null)
                    {
                        var ressel = toolwin.SelectedResource.Replace(_rootProject, "");
                        var keys = EnvPhoneDevice.PhoneLanguageSupport().Keys.ToArray();
                        foreach (var key in keys)
                        {
                            var index = ressel.IndexOf("." + key + ".", StringComparison.InvariantCultureIgnoreCase);
                            if (index < 0)
                            {
                                index = ressel.IndexOf("." + key.Substring(0, 2) + ".",
                                                        StringComparison.InvariantCultureIgnoreCase);
                            }
                            if (index > 0)
                            {
                                var neutalres = ressel.Substring(0, index);
                                index = ressel.LastIndexOf(".", StringComparison.Ordinal);
                                neutalres += ressel.Substring(index);
                                CboFilesResx.SelectedItem = neutalres;
                                break;
                            }
                        }
                        if (CboFilesResx.SelectedItem == null)
                        {
                            CboFilesResx.SelectedItem = ressel;
                        }
                    }
                }
            }
            else
            {
                CboFilesResx.IsEnabled = false;
            }
            ValidateFields();
            IsEnabled = true;
            Waitresx.Visibility = Visibility.Collapsed;
            _loaded = true;
        }

        private void TranslateResxControlSizeChanged(object sender, SizeChangedEventArgs e)
        {
            DGResx.Width = GrdMain.ActualWidth - 30;
            GrdCmd.Width = GrdMain.ActualWidth - 30;
        }

        private void CboFilesResxSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DGResx.ItemsSource = null;
            DGResx.Columns.Clear();
            BntTargetFolder.Visibility = Visibility.Hidden;
            if (e.AddedItems == null || e.AddedItems.Count == 0 || CboPrjLng.SelectedIndex == -1)
            {
                return;
            }

            var seletedProject = EnvPhoneDevice.FindProjectByName(Package.EnvDte, _projectName);

            // ReSharper disable PossibleNullReferenceException
            var defres = _rootProject + (string)e.AddedItems[0];
            // ReSharper restore PossibleNullReferenceException
            var fi = new FileInfo(defres);
            var fname = fi.Name.Replace(fi.Extension, "");
            var lngs = new List<string>();

            // ReSharper disable PossibleNullReferenceException
            var prjfolderitem = EnvPhoneDevice.FolderExistProject(seletedProject, fi.Directory.FullName.Replace(_rootProject, ""));
            // ReSharper restore PossibleNullReferenceException

            if (prjfolderitem == null && (fi.Directory.FullName + "\\") == _rootProject)
            {
                //ROOT FOLDER
                lngs.AddRange(from projectItem in seletedProject.ProjectItems.OfType<ProjectItem>() select (projectItem).Properties.Item("FullPath").Value.ToString() into fullname let finf = new FileInfo(fullname) where finf.Name.StartsWith(fname) && finf.Name.EndsWith(fi.Extension) && finf.Name != fi.Name select fullname);
            }
            else
            {
                if (prjfolderitem != null)
                {
                    lngs.AddRange(from projectItem in prjfolderitem.ProjectItems.OfType<ProjectItem>() select (projectItem).Properties.Item("FullPath").Value.ToString() into fullname let finf = new FileInfo(fullname) where finf.Name.StartsWith(fname) && finf.Name.EndsWith(fi.Extension) && finf.Name != fi.Name select fullname);
                }
            }

            _filesLangResources = lngs.ToArray();

            if (_filesLangResources.Length == 0)
            {
                CboPrjLng.IsEnabled = true;
                CboFilesResx.IsEnabled = true;
                BntTargetFolder.Visibility = Visibility.Visible;
                return;
            }

            if (ValidateFields() == 0)
            {
                CboPrjLng.IsEnabled = false;
                CboFilesResx.IsEnabled = false;

                var oldcur = Cursor;
                Cursor = Cursors.Wait;
                CreateResxCollection(fi.FullName, oldcur);
            }

        }

        private static int Adorne(Control control, bool error, string tootip)
        {
            if (error)
            {
                var colorerr = VsTheming.GetColorError();
                if (!control.BorderBrush.Equals(colorerr))
                {
                    control.Tag = control.BorderBrush;
                    control.BorderBrush = colorerr;
                    control.ToolTip = tootip;
                }
                return 1;
            }
            if (!control.BorderBrush.Equals(control.Tag) && control.Tag != null)
            {
                control.BorderBrush = (Brush)control.Tag;
            }
            return 0;
        }

        private int ValidateFields()
        {
            var qtd = 0;
            qtd += Adorne(CboPrjLng, CboPrjLng.SelectedItem == null, AppRes.RequiredField);
            qtd += Adorne(CboFilesResx, CboFilesResx.SelectedItem == null, AppRes.RequiredField);
            return qtd;
        }

        private void CboFilesResxLostFocus(object sender, RoutedEventArgs e)
        {
            if (CboFilesResx.IsDropDownOpen) return;
            ValidateFields();
        }

        private void CboPrjLngLostFocus(object sender, RoutedEventArgs e)
        {
            if (CboPrjLng.IsDropDownOpen) return;
            ValidateFields();
        }

        private void CreateResxCollection(string neutalfilename, Cursor oldcur)
        {
            try
            {
                //clear counts
                _qtdKeyOrph = 0;
                _qtdTargetNOk = 0;
                var dataSource = new List<ModelResxTranslateAll>();
                _headerLngs = new List<KeyValuePair<string, string>>();

                ITypeResolutionService typeres = null;

                #region populate Model with neutral file

                var readerResFile = new ResXResourceReader(neutalfilename) { UseResXDataNodes = true };
                var qtdsource = 0;
                foreach (DictionaryEntry d in readerResFile)
                {
                    qtdsource++;
                    var isvalidvalue = true;
                    var node = (ResXDataNode)d.Value;
                    object value = string.Empty;
                    try
                    {
                        // ReSharper disable ExpressionIsAlwaysNull
                        value = node.GetValue(typeres) ?? string.Empty;
                        // ReSharper restore ExpressionIsAlwaysNull
                    }
                    catch
                    {
                        isvalidvalue = false;
                    }
                    var model = new ModelResxTranslateAll();
                    model.GetType().GetProperty("KeyOrphans").SetValue(model, false, null);
                    model.GetType().GetProperty("Key").SetValue(model, d.Key.ToString(), null);
                    model.GetType().GetProperty("Comment").SetValue(model, node.Comment, null);
                    if (isvalidvalue)
                    {
                        model.GetType().GetProperty("IsValidString").SetValue(model, true, null);
                        model.GetType().GetProperty("SourceValue").SetValue(model, value.ToString(), null);
                        model.GetType().GetProperty("OriginalValue").SetValue(model, value.ToString(), null);
                    }
                    else
                    {
                        model.GetType().GetProperty("IsValidString").SetValue(model, false, null);
                        // ReSharper disable PossibleNullReferenceException
                        model.GetType().GetProperty("SourceValue").SetValue(model, node.FileRef.ToString(), null);
                        model.GetType().GetProperty("OriginalValue").SetValue(model, node, null);
                        qtdsource--;
                    }
                    dataSource.Add(model);
                }
                readerResFile.Close();

                #endregion

                #region populate language resources

                var keys = EnvPhoneDevice.PhoneLanguageSupport().Keys.ToArray();
                var qtdPrgBarmMax = 0;
                var qtdPrgBarValue = 0;
                foreach (var item in _filesLangResources)
                {
                    var fname = new FileInfo(item).Name;
                    var modelColTarget = string.Empty;
                    foreach (var key in keys)
                    {
                        var index = fname.IndexOf("." + key + ".", StringComparison.InvariantCultureIgnoreCase);
                        if (index < 0)
                        {
                            index = fname.IndexOf("." + key.Substring(0, 2) + ".",
                                                  StringComparison.InvariantCultureIgnoreCase);
                        }
                        if (index > 0)
                        {
                            modelColTarget = key;
                            break;
                        }
                    }
                    if (!string.IsNullOrEmpty(modelColTarget))
                    {
                        var header = EnvPhoneDevice.GetValuePhoneLanguageSupport(modelColTarget);
                        if (string.IsNullOrEmpty(header))
                        {
                            header = AppRes.Unknown;
                        }
                        _headerLngs.Add(new KeyValuePair<string, string>(modelColTarget, header));
                        var edtfield = "Value_" + modelColTarget.Replace("-", "_");
                        var orifield = "Original_" + modelColTarget.Replace("-", "_");
                        readerResFile = new ResXResourceReader(item) { UseResXDataNodes = true };
                        _qtdTargetNOk += qtdsource;
                        qtdPrgBarmMax += qtdsource;
                        foreach (DictionaryEntry d in readerResFile)
                        {
                            var node = (ResXDataNode)d.Value;
                            var found = dataSource.FirstOrDefault(i => i.Key == d.Key.ToString());
                            if (found != null)
                            {
                                if (found.IsValidString)
                                {
                                    // ReSharper disable ExpressionIsAlwaysNull
                                    var value = node.GetValue(typeres);
                                    // ReSharper restore ExpressionIsAlwaysNull
                                    found.GetType().GetProperty(edtfield).SetValue(found, value.ToString(), null);
                                    found.GetType().GetProperty(orifield).SetValue(found, value.ToString(), null);
                                    if (!string.IsNullOrEmpty(value.ToString()))
                                    {
                                        _qtdTargetNOk--;
                                        qtdPrgBarValue++;
                                    }
                                }
                                else
                                {
                                    found.GetType().GetProperty(edtfield).SetValue(found, node.FileRef.ToString(), null);
                                    found.GetType().GetProperty(orifield).SetValue(found, node, null);
                                }
                            }
                            else
                            {
                                var isvalidvalue = true;
                                object value = string.Empty;
                                try
                                {
                                    // ReSharper disable ExpressionIsAlwaysNull
                                    value = node.GetValue(typeres);
                                    // ReSharper restore ExpressionIsAlwaysNull
                                }
                                catch
                                {
                                    isvalidvalue = false;
                                }
                                _qtdKeyOrph++;
                                var model = new ModelResxTranslateAll();
                                model.GetType().GetProperty("KeyOrphans").SetValue(model, true, null);
                                model.GetType().GetProperty("Key").SetValue(model, d.Key.ToString(), null);
                                if (isvalidvalue)
                                {
                                    model.GetType().GetProperty("IsValidString").SetValue(model, true, null);
                                    model.GetType().GetProperty(edtfield).SetValue(model, value.ToString(), null);
                                    model.GetType().GetProperty(orifield).SetValue(model, value.ToString(), null);
                                }
                                else
                                {
                                    model.GetType().GetProperty("IsValidString").SetValue(model, false, null);
                                    // ReSharper disable PossibleNullReferenceException
                                    model.GetType().GetProperty(edtfield).SetValue(model, node.FileRef.ToString(), null);
                                    model.GetType().GetProperty(orifield).SetValue(model, node, null);
                                    // ReSharper restore PossibleNullReferenceException
                                }
                                dataSource.Insert(0, model);
                            }
                        }
                        readerResFile.Close();
                    }
                }

                #endregion

                #region create Collumns in DataGrid

                DGResx.Columns.Clear();


                var headerStyle = new Style(typeof(DataGridColumnHeader));
                headerStyle.Setters.Add(new Setter(HorizontalAlignmentProperty, HorizontalAlignment.Stretch));
                headerStyle.Setters.Add(new Setter(HorizontalContentAlignmentProperty, HorizontalAlignment.Center));
                headerStyle.Setters.Add(new Setter(TextBlock.TextWrappingProperty, TextWrapping.NoWrap));
                headerStyle.Setters.Add(new Setter(MarginProperty, new Thickness(5)));

                var keyStyle = new Style(typeof(TextBlock));
                keyStyle.Setters.Add(new Setter(TextBlock.TextWrappingProperty, TextWrapping.WrapWithOverflow));
                keyStyle.Setters.Add(new Setter(VerticalAlignmentProperty, VerticalAlignment.Center));
                keyStyle.Setters.Add(new Setter(MarginProperty, new Thickness(5)));

                var textStyle = new Style(typeof(TextBlock));
                textStyle.Setters.Add(new Setter(TextBlock.TextWrappingProperty, TextWrapping.Wrap));
                textStyle.Setters.Add(new Setter(VerticalAlignmentProperty, VerticalAlignment.Center));
                textStyle.Setters.Add(new Setter(MarginProperty, new Thickness(5)));

                var editStyle = new Style(typeof(TextBox));
                textStyle.Setters.Add(new Setter(TextBlock.TextWrappingProperty, TextWrapping.Wrap));
                textStyle.Setters.Add(new Setter(VerticalAlignmentProperty, VerticalAlignment.Center));
                textStyle.Setters.Add(new Setter(MarginProperty, new Thickness(5)));

                var orphansEditStyle = new Style(typeof(CheckBox));
                orphansEditStyle.Setters.Add(new Setter(VerticalAlignmentProperty, VerticalAlignment.Center));
                orphansEditStyle.Setters.Add(new Setter(HorizontalAlignmentProperty, HorizontalAlignment.Center));
                orphansEditStyle.Setters.Add(new Setter(IsEnabledProperty, false));


                var orphansStyle = new Style(typeof(CheckBox));
                orphansStyle.Setters.Add(new Setter(VerticalAlignmentProperty, VerticalAlignment.Center));
                orphansStyle.Setters.Add(new Setter(HorizontalAlignmentProperty, HorizontalAlignment.Center));
                orphansStyle.Setters.Add(new Setter(IsEnabledProperty, false));
                var boolcolumn = new DataGridCheckBoxColumn
                                     {
                                         CanUserReorder = false,
                                         CanUserResize = false,
                                         Header = AppRes.XOrphans,
                                         Binding = new Binding("KeyOrphans"),
                                         MinWidth = 50,
                                         IsReadOnly = false,
                                         ElementStyle = orphansStyle,
                                         EditingElementStyle = orphansEditStyle,
                                         HeaderStyle = headerStyle
                                     };
                DGResx.Columns.Add(boolcolumn);

                var textcolumn = new DataGridTextColumn
                                     {
                                         CanUserReorder = false,
                                         CanUserResize = false,
                                         Header = AppRes.XColKey,
                                         Binding = new Binding("Key"),
                                         IsReadOnly = false,
                                         MinWidth = 170,
                                         Width = new DataGridLength(20, DataGridLengthUnitType.Star),
                                         ElementStyle = textStyle,
                                         EditingElementStyle = editStyle,
                                         HeaderStyle = headerStyle
                                     };
                DGResx.Columns.Add(textcolumn);

                textcolumn = new DataGridTextColumn
                                 {
                                     CanUserReorder = false,
                                     CanUserResize = false,
                                     Header = CboPrjLng.Text,
                                     Binding = new Binding("SourceValue"),
                                     IsReadOnly = false,
                                     MinWidth = 200,
                                     Width = new DataGridLength(40, DataGridLengthUnitType.Star),
                                     ElementStyle = textStyle,
                                     EditingElementStyle = editStyle,
                                     HeaderStyle = headerStyle
                                 };
                DGResx.Columns.Add(textcolumn);

                //fist fileselct
                var toolwin = (WpcTranslteToolWindow)_parentWindow;
                var firstlng = string.Empty;
                if (!string.IsNullOrEmpty(toolwin.SelectedResource))
                {
                    var fname = new FileInfo(toolwin.SelectedResource).Name;
                    foreach (var item in _headerLngs)
                    {
                        var ok = false;
                        if (fname.Contains("." + item.Key + "."))
                        {
                            ok = true;
                        }
                        else
                        {
                            if (fname.Contains("." + item.Key.Substring(0, 2) + "."))
                            {
                                ok = true;
                            }
                        }
                        if (ok)
                        {
                            var keyfield = "Value_" + item.Key.Replace("-", "_");
                            textcolumn = new DataGridTextColumn
                                             {
                                                 CanUserReorder = true,
                                                 CanUserResize = false,
                                                 Header = item.Value,
                                                 Binding = new Binding(keyfield),
                                                 IsReadOnly = false,
                                                 MinWidth = 200,
                                                 Width = new DataGridLength(40, DataGridLengthUnitType.Star),
                                                 ElementStyle = textStyle,
                                                 EditingElementStyle = editStyle,
                                                 HeaderStyle = headerStyle
                                             };
                            DGResx.Columns.Add(textcolumn);
                            firstlng = item.Key;
                            break;
                        }
                    }
                }

                foreach (var collng in _headerLngs)
                {
                    if (collng.Key != firstlng)
                    {
                        var keyfield = "Value_" + collng.Key.Replace("-", "_");
                        textcolumn = new DataGridTextColumn
                        {
                            CanUserReorder = true,
                            CanUserResize = false,
                            Header = collng.Value,
                            Binding = new Binding(keyfield),
                            IsReadOnly = false,
                            MinWidth = 200,
                            Width = new DataGridLength(40, DataGridLengthUnitType.Star),
                            ElementStyle = textStyle,
                            EditingElementStyle = editStyle,
                            HeaderStyle = headerStyle
                        };
                        DGResx.Columns.Add(textcolumn);
                    }
                }

                #endregion

                BntTran.IsEnabled = (_qtdTargetNOk > 0);
                BntNewTarget.IsEnabled = true;
                BntSave.IsEnabled = true;
                ChkSync.IsEnabled = (_qtdKeyOrph > 0);

                QtdOrph.Text = _qtdKeyOrph.ToString(CultureInfo.InvariantCulture);
                QtdTotrans.Text = _qtdTargetNOk.ToString(CultureInfo.InvariantCulture);

                PrgbarTrans.Minimum = 0;
                PrgbarTrans.Maximum = qtdPrgBarmMax;
                PrgbarTrans.Value = qtdPrgBarValue;
                DGResx.ItemsSource = null;
                DGResx.FrozenColumnCount = 3;
                DGResx.ItemsSource = dataSource;

            }
            catch (Exception ex)
            {
                Cursor = oldcur;
                DGResx.ItemsSource = null;
                MessageBox.Show(ex.Message, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Error);
            }
            Cursor = oldcur;
            IsEnabled = true;
        }

        private void DgResxLoadingRow(object sender, DataGridRowEventArgs e)
        {
            // Get the DataRow corresponding to the DataGridRow that is loading.
            var item = e.Row.Item as ModelResxTranslateAll;
            if (item != null)
            {
                if (item.IsValidString)
                {
                    e.Row.Foreground = item.KeyOrphans ? VsTheming.GetColorError() : VsTheming.GetWindowText();
                }
                else
                {
                    e.Row.Foreground = VsTheming.GetWindowDisabledText();
                }
            }
        }

        private void BntTranClick(object sender, RoutedEventArgs e)
        {
            if (_workerTranlate != null)
            {
                if (_workerTranlate.CancellationPending)
                {
                    return;
                }
                if (_workerTranlate.IsBusy)
                {
                    _workerTranlate.CancelAsync();
                    return;
                }
            }

            switch (UserSettings.Current.EngineTranslate)
            {
                case EngineTranslate.Google:
                    break;
                case EngineTranslate.Bing:
                    {
                        if (!UserSettings.Current.HasBingCredencial)
                        {
                            new BingTranslatorInfoDialog().ShowModal();
                            return;
                        }
                    }
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            if (UserSettings.Current.PromptPwd)
            {
                var dialog = new PwdDialog();
                dialog.ShowModal();
                if (string.IsNullOrEmpty(dialog.Key))
                {
                    MessageBox.Show(AppRes.PwdEmpty, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                if (dialog.Key != EncryptDecryptMd5.DecryptString(UserSettings.Current.Md5Password, Constants.GuidRef))
                {
                    MessageBox.Show(AppRes.PwdInvalid, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
            }

            var oldcur = Cursor;

            var stateNewtarget = BntNewTarget.IsEnabled;
            var stateChkSync = ChkSync.IsEnabled;
            var stateSave = BntSave.IsEnabled;

            BntNewTarget.IsEnabled = false;
            ChkSync.IsEnabled = false;
            BntSave.IsEnabled = false;
            TextRunTranslation.Text = AppRes.CancelTrans;
            DGResx.IsReadOnly = true;

            var sourcelng = EnvPhoneDevice.GetKeyPhoneLanguageSupport((string)CboPrjLng.SelectedItem);

            //get dispatcher
            var pdDispatcher = Dispatcher;

            //create background worker and support cancellation
            _workerTranlate = new BackgroundWorker { WorkerSupportsCancellation = true };

            _workerTranlate.RunWorkerCompleted += (o, args) =>
            {
                Cursor = oldcur;
                DGResx.Items.Refresh();
                DGResx.IsReadOnly = false;
                BntNewTarget.IsEnabled = stateNewtarget;
                ChkSync.IsEnabled = stateChkSync;
                BntSave.IsEnabled = stateSave;
                TextRunTranslation.Text = AppRes.XRunTranslation;
                BntTran.IsEnabled = (_qtdTargetNOk > 0);
                IsEnabled = true;
            };

            _workerTranlate.DoWork += (s, args) =>
            {
                try
                {
                    foreach (var itemdg in DGResx.Items)
                    {
                        if (_workerTranlate.CancellationPending || args.Cancel)
                        {
                            args.Cancel = true;
                            break;
                        }
                        var item = itemdg as ModelResxTranslateAll;
                        if (item == null)
                        {
                            continue;
                        }
                        if (!item.KeyOrphans && item.IsValidString)
                        {
                            var sourcevalue =
                                item.GetType().GetProperty("SourceValue").GetValue(item,
                                                                                    null) ??
                                string.Empty;
                            if (!string.IsNullOrEmpty(sourcevalue.ToString()))
                            {
                                foreach (var collng in _headerLngs)
                                {
                                    var itemtype = item.GetType();
                                    var keyfield = "Value_" + collng.Key.Replace("-", "_");
                                    if (_workerTranlate.CancellationPending)
                                    {
                                        args.Cancel = true;
                                        break;
                                    }
                                    var value =
                                        itemtype.GetProperty(keyfield).GetValue(item, null) ??
                                        string.Empty;
                                    if (string.IsNullOrEmpty(value.ToString()))
                                    {
                                        var targetlng = collng.Key;
                                        string newvalue;
                                        string errortranslate;
                                        switch (UserSettings.Current.EngineTranslate)
                                        {
                                            case EngineTranslate.Google:
                                                newvalue =
                                                    GoogleTranslate.TranslateText(
                                                        sourcevalue.ToString(),
                                                        sourcelng.Substring(0, 2),
                                                        targetlng.Substring(0, 2),
                                                        out errortranslate);
                                                break;
                                            case EngineTranslate.Bing:
                                                newvalue =
                                                    BingTranslate.TranslateText(
                                                        sourcevalue.ToString(),
                                                        sourcelng.Substring(0, 2),
                                                        targetlng.Substring(0, 2),
                                                        out errortranslate);
                                                break;
                                            default:
                                                throw new ArgumentOutOfRangeException();
                                        }
                                        if (!string.IsNullOrEmpty(errortranslate))
                                        {
                                            throw new Exception(errortranslate);
                                        }
                                        if (!string.IsNullOrEmpty(newvalue))
                                        {
                                            itemtype.GetProperty(keyfield).SetValue(item,
                                                                                    newvalue,
                                                                                    null);
                                            _qtdTargetNOk--;
                                            //invoke the dispatcher to update ui
                                            pdDispatcher.BeginInvoke(
                                                new UpdateProgressDelegate(UpdateProgress),
                                                1);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    args.Cancel = true;
                    pdDispatcher.BeginInvoke(new UpdateCursorDelegate(UpdateCursor),
                                            oldcur);
                    MessageBox.Show(AppRes.ErrEngine, AppRes.ToolWindowTitle,
                                    MessageBoxButton.OK, MessageBoxImage.Error);
                }
            };

            //run the process
            _workerTranlate.RunWorkerAsync();
        }

        //Delegate used for updating the UI
        private delegate void UpdateProgressDelegate(int value);

        //Delegate used for updating the cursor
        private delegate void UpdateCursorDelegate(Cursor cur);

        private void UpdateCursor(Cursor cur)
        {
            Cursor = cur;
        }

        private void UpdateProgress(int value)
        {
            QtdTotrans.Text = _qtdTargetNOk.ToString(CultureInfo.InvariantCulture);
            PrgbarTrans.Value += value;
        }

        private void DgResxBeginningEdit(object sender, DataGridBeginningEditEventArgs e)
        {
            var item = e.Row.Item as ModelResxTranslateAll;
            if (item != null)
            {
                if (item.KeyOrphans || !item.IsValidString)
                {
                    e.Cancel = true;
                }
            }
            if (e.Column.DisplayIndex == 0)
            {
                DGResx.CommitEdit();
            }
            BntTran.IsEnabled = (_qtdTargetNOk > 0);
        }

        private void DgResxPreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e)
        {
            if (e.Column.DisplayIndex == 0)
            {
                var chk = e.EditingElement as CheckBox;
                chk.IsEnabled = false;
            }
            else
            {
                ((TextBox)e.EditingElement).TextWrapping = TextWrapping.Wrap;
            }
        }

        private void RefreshItens()
        {
            DGResx.Items.Refresh();
            QtdTotrans.Text = _qtdTargetNOk.ToString(CultureInfo.InvariantCulture);
        }

        private void DgResxCellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            var item = e.Row.Item as ModelResxTranslateAll;
            if (item != null)
            {
                var issource = false;
                var iskey = false;
                var origfield = string.Empty;
                var editfield = e.Column.SortMemberPath;
                //checkbox - orph. or key
                if (e.Column.DisplayIndex == 0 || e.Column.DisplayIndex == 1)
                {
                    origfield = editfield;
                }
                if (e.Column.DisplayIndex == 1)
                {
                    iskey = true;
                }
                else
                {
                    if (editfield == "SourceValue")
                    {
                        origfield = "OriginalValue";
                        issource = true;
                    }
                    else if (editfield.StartsWith("Value_"))
                    {
                        origfield = "Original_" + editfield.Replace("Value_", "");
                    }
                }

                var valueori = item.GetType().GetProperty(origfield).GetValue(item, null) ?? string.Empty;
                var valueedt = item.GetType().GetProperty(editfield).GetValue(item, null) ?? string.Empty;

                string newvalue;
                if (e.EditingElement is TextBox)
                {
                    newvalue = ((TextBox)e.EditingElement).Text;
                    if (newvalue.Trim().Length == 0)
                    {
                        newvalue = string.Empty;
                    }
                }
                else
                {
                    //checkbox orph;
                    newvalue = valueori.ToString();
                }
                if (iskey && string.IsNullOrEmpty(newvalue))
                {
                    MessageBox.Show(AppRes.ErrEmptyKeyValue, AppRes.ToolWindowTitle, MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                    ((TextBox)e.EditingElement).Text = valueedt.ToString();
                    return;
                }
                if (iskey)
                {
                    var existskey = false;
                    // ReSharper disable LoopCanBeConvertedToQuery
                    foreach (var itemdg in DGResx.Items)
                    // ReSharper restore LoopCanBeConvertedToQuery
                    {
                        var it = itemdg as ModelResxTranslateAll;
                        if (it != null)
                        {
                            if (it.Key.ToLower() == newvalue.ToLower())
                            {
                                if (!it.Equals(DGResx.SelectedItem))
                                {
                                    existskey = true;
                                }
                                break;
                            }
                        }
                    }
                    if (existskey)
                    {
                        MessageBox.Show(AppRes.ErrKeyExists, AppRes.ToolWindowTitle, MessageBoxButton.OK,
                                        MessageBoxImage.Error);
                        ((TextBox)e.EditingElement).Text = valueedt.ToString();
                        return;
                    }
                }
                if (iskey)
                {
                    item.GetType().GetProperty("Key").SetValue(item, newvalue, null);
                    return;
                }

                if (issource && string.IsNullOrEmpty(newvalue))
                {
                    MessageBox.Show(AppRes.ErrEmptyValueNeutralResx, AppRes.ToolWindowTitle, MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                    ((TextBox)e.EditingElement).Text = valueedt.ToString();
                    return;
                }

                var editingElement = e.EditingElement as TextBox;
                if (editingElement != null)
                {
                    (editingElement).Text = newvalue;
                }

                if (!string.IsNullOrEmpty(valueori.ToString()))
                {
                    if (valueori.Equals(valueedt))
                    {
                        if (!valueori.Equals(newvalue))
                        {
                            if (issource)
                            {
                                for (var i = 3; i < DGResx.Columns.Count; i++)
                                {
                                    var col = DGResx.Columns[i];
                                    var valuecol =
                                        item.GetType().GetProperty(col.SortMemberPath).GetValue(item, null) ??
                                        string.Empty;
                                    if (!string.IsNullOrEmpty(valuecol.ToString()))
                                    {
                                        _qtdTargetNOk++;
                                        item.GetType().GetProperty(col.SortMemberPath).SetValue(item, null, null);
                                    }
                                }
                                Dispatcher.BeginInvoke(new Action(RefreshItens), DispatcherPriority.ApplicationIdle,
                                                       null);
                            }
                        }
                    }
                    else
                    {
                        if (!valueori.Equals(newvalue))
                        {
                            if (issource)
                            {
                                for (var i = 3; i < DGResx.Columns.Count; i++)
                                {
                                    var col = DGResx.Columns[i];
                                    var valuecol =
                                        item.GetType().GetProperty(col.SortMemberPath).GetValue(item, null) ??
                                        string.Empty;
                                    if (!string.IsNullOrEmpty(valuecol.ToString()))
                                    {
                                        _qtdTargetNOk++;
                                        item.GetType().GetProperty(col.SortMemberPath).SetValue(item, null, null);
                                    }
                                }
                                Dispatcher.BeginInvoke(new Action(RefreshItens), DispatcherPriority.ApplicationIdle,
                                                       null);
                            }
                        }
                    }
                    if (!issource)
                    {
                        if (string.IsNullOrEmpty(valueedt.ToString()) && !string.IsNullOrEmpty(newvalue))
                        {
                            _qtdTargetNOk--;
                        }
                        if (!string.IsNullOrEmpty(valueedt.ToString()) && string.IsNullOrEmpty(newvalue))
                        {
                            _qtdTargetNOk++;
                        }
                    }
                    BntTran.IsEnabled = (_qtdTargetNOk > 0);
                    QtdTotrans.Text = _qtdTargetNOk.ToString(CultureInfo.InvariantCulture);
                }
            }
        }

        private void BntNewTargetClick(object sender, RoutedEventArgs e)
        {
            // ReSharper disable PossibleInvalidOperationException
            if ((_qtdKeyOrph > 0 && ChkSync.IsChecked.Value) || (_qtdTargetNOk > 0))
            // ReSharper restore PossibleInvalidOperationException
            {
                var result = MessageBox.Show(AppRes.QSaveDelOrphNotTranslated, AppRes.ToolWindowTitle,
                                                MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result == MessageBoxResult.No)
                {
                    return;
                }
            }
            _qtdKeyOrph = 0;
            _qtdTargetNOk = 0;
            _filesLangResources = new string[] { };
            DGResx.ItemsSource = null;
            DGResx.Columns.Clear();
            BntTran.IsEnabled = false;
            BntSave.IsEnabled = false;
            ChkSync.IsEnabled = false;
            BntNewTarget.IsEnabled = false;
            CboFilesResx.IsEnabled = true;
            CboFilesResx.SelectedItem = null;
            BntTargetFolder.Visibility = Visibility.Hidden;
            QtdOrph.Text = "0";
            QtdTotrans.Text = "0";
            PrgbarTrans.Value = 0;
        }

        private void DgResxCurrentCellChanged(object sender, EventArgs e)
        {
            DGResx.ScrollIntoView(DGResx.CurrentCell.Item, DGResx.CurrentCell.Column);
        }

        private void CboPrjLngSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems == null || e.AddedItems.Count == 0)
            {
                CboFilesResx.SelectedItem = null;
                CboFilesResx.IsEnabled = false;
                _filesLangResources = new string[] { };
            }
            else
            {
                CboFilesResx.IsEnabled = true;
            }
        }

        private void BntTargetFolderClick(object sender, RoutedEventArgs e)
        {
            // ReSharper disable PossibleNullReferenceException
            var defres = _rootProject + CboFilesResx.SelectedItem;
            // ReSharper restore PossibleNullReferenceException
            var fi = new FileInfo(defres);

            var seletedProject = EnvPhoneDevice.FindProjectByName(Package.EnvDte, _projectName);
            var dialog = new TargetFolderDialog { SelectedProject = seletedProject, ParentWindow = _parentWindow, NeutralFile = fi.Name };
            dialog.ShowModal();
            if (dialog.SelectFolder == null)
            {
                return;
            }

            _filesLangResources = dialog.SelectFolder.ToArray();

            CboPrjLng.IsEnabled = false;
            CboFilesResx.IsEnabled = false;

            var oldcur = Cursor;
            Cursor = Cursors.Wait;
            IsEnabled = false;
            Dispatcher.BeginInvoke(new Action<string, Cursor>(CreateResxCollection), DispatcherPriority.Normal,
                                   new object[] { fi.FullName, oldcur });

        }

        private void DgResxPreviewMouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            var dep = (DependencyObject)e.OriginalSource;

            // iteratively traverse the visual tree
            while ((dep != null) && !(dep is DataGridCell) && !(dep is DataGridColumnHeader))
            {
                dep = VisualTreeHelper.GetParent(dep);
            }

            if (dep == null)
                return;


            //if (dep is DataGridColumnHeader)
            //{
            //    var columnHeader = dep as DataGridColumnHeader;
            //}

            if (dep is DataGridCell)
            {
                var cell = dep as DataGridCell;

                if (cell.IsEditing)
                {
                    return;
                }

                var ctxmenu = new ContextMenu();
                var menuNewKey = new MenuItem { Header = "New key Resource" };
                menuNewKey.Click += (s, r) =>
                {
                    var item = DGResx.Items[DGResx.Items.Count - 1];
                    DGResx.ScrollIntoView(item, DGResx.Columns[0]);
                    DGResx.SelectedIndex = DGResx.Items.Count - 1;
                    var selrow = (DataGridRow)DGResx.ItemContainerGenerator.ContainerFromIndex(DGResx.SelectedIndex);
                    selrow.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                    DGResx.BeginEdit();
                };
                ctxmenu.Items.Add(menuNewKey);

                if (cell.Column.DisplayIndex >= 2)
                {
                    var editfield = cell.Column.SortMemberPath;
                    var origfiled = string.Empty;
                    if (editfield == "SourceValue")
                    {
                        origfiled = "OriginalValue";
                    }
                    else if (editfield.StartsWith("Value_"))
                    {
                        origfiled = "Original_" + editfield.Replace("Value_", "");
                    }

                    // navigate further up the tree
                    while ((dep != null) && !(dep is DataGridRow))
                    {
                        dep = VisualTreeHelper.GetParent(dep);
                    }
                    if (dep != null)
                    {
                        var row = dep as DataGridRow;
                        if (!(row.Item is ModelResxTranslateAll))
                        {
                            return;
                        }
                        if (((ModelResxTranslateAll)row.Item).KeyOrphans)
                        {
                            return;
                        }

                        var valueori = row.Item.GetType().GetProperty(origfiled).GetValue(row.Item, null) ?? string.Empty;
                        var valueedt = row.Item.GetType().GetProperty(editfield).GetValue(row.Item, null) ?? string.Empty;

                        if (string.IsNullOrEmpty(valueedt.ToString()) && cell.Column.DisplayIndex > 2)
                        {
                            var titHeader = cell.Column.Header.ToString();
                            var menuTranslate = new MenuItem { Header = string.Format(AppRes.MenuTransTo, titHeader) };
                            menuTranslate.Click += (s, r) =>
                            {
                            };
                            ctxmenu.Items.Add(menuTranslate);
                        }

                        if (!valueori.Equals(valueedt))
                        {
                            var menuRecover = new MenuItem { Header = AppRes.RecoverOriginalVakue };


                            if (cell.Column.DisplayIndex > 2)
                            {


                                menuRecover.Click += (s, r) =>
                                {
                                    row.Item.GetType().GetProperty(editfield).SetValue(row.Item, valueori, null);
                                    if (string.IsNullOrEmpty(valueori.ToString()))
                                    {
                                        _qtdTargetNOk++;
                                    }
                                    else if (string.IsNullOrEmpty(valueedt.ToString()) && !string.IsNullOrEmpty(valueori.ToString()))
                                    {
                                        _qtdTargetNOk--;
                                    }
                                    Dispatcher.BeginInvoke(new Action(RefreshItens), DispatcherPriority.ApplicationIdle, null);
                                };

                                ctxmenu.Items.Add(menuRecover);
                            }
                            else if (cell.Column.DisplayIndex == 2)
                            {
                                menuRecover.Click += (s, r) =>
                                {
                                    row.Item.GetType().GetProperty(editfield).SetValue(row.Item, valueori, null);
                                    for (var i = 3; i < DGResx.Columns.Count; i++)
                                    {
                                        var col = DGResx.Columns[i];
                                        var valuecoledt =
                                            row.Item.GetType().GetProperty(col.SortMemberPath).GetValue(row.Item, null) ??
                                            string.Empty;
                                        var colorifiled = "Original_" + col.SortMemberPath.Replace("Value_", "");
                                        var valuecolori =
                                            row.Item.GetType().GetProperty(colorifiled).GetValue(row.Item, null) ??
                                            string.Empty;
                                        if (!valuecolori.Equals(valuecoledt))
                                        {
                                            row.Item.GetType().GetProperty(col.SortMemberPath).SetValue(row.Item, valuecolori, null);
                                            if (string.IsNullOrEmpty(valuecolori.ToString()))
                                            {
                                                _qtdTargetNOk++;
                                            }
                                            else if (string.IsNullOrEmpty(valuecoledt.ToString()) && !string.IsNullOrEmpty(valuecolori.ToString()))
                                            {
                                                _qtdTargetNOk--;
                                            }
                                        }
                                    }
                                    Dispatcher.BeginInvoke(new Action(RefreshItens), DispatcherPriority.ApplicationIdle, null);
                                };
                                ctxmenu.Items.Add(menuRecover);
                            }
                        }
                        DGResx.SelectedIndex = row.GetIndex();
                    }
                }
                if (ctxmenu.Items.Count > 0)
                {
                    ctxmenu.IsOpen = true;
                }
            }
        }

        private void TranslateResxControlUnloaded(object sender, RoutedEventArgs e)
        {
            if (_workerTranlate != null)
            {
                if (_workerTranlate.IsBusy)
                {
                    if (!_workerTranlate.CancellationPending)
                    {
                        _workerTranlate.CancelAsync();
                    }
                }
            }
        }

        private void BntSaveClick(object sender, RoutedEventArgs e)
        {
            var oldcur = Cursor;
            IsEnabled = false;
            Dispatcher.BeginInvoke(new Action<Cursor>(SaveResources), DispatcherPriority.ApplicationIdle, new object[] { oldcur });
        }

        private void SaveResources(Cursor cur)
        {
            Cursor = Cursors.Wait;
            try
            {
                var savelngs = _headerLngs.ToList();
                // ReSharper disable PossibleNullReferenceException
                var defneutral = _rootProject + (string)CboFilesResx.SelectedItem;
                // ReSharper restore PossibleNullReferenceException
                var fineutral = new FileInfo(defneutral);
                var keyneutral = EnvPhoneDevice.GetKeyPhoneLanguageSupport((string)CboPrjLng.SelectedItem);
                savelngs.Insert(0, new KeyValuePair<string, string>(keyneutral, fineutral.FullName));
                foreach (var lng in savelngs)
                {
                    string file;
                    if (lng.Key == keyneutral)
                    {
                        file = lng.Value;
                    }
                    else
                    {
                        file = _filesLangResources.FirstOrDefault(f => f.Contains("." + lng.Key + ".")) ??
                                   _filesLangResources.FirstOrDefault(f => f.Contains("." + lng.Key.Substring(0, 2) + "."));
                    }
                    if (file != null)
                    {
                        var prjitem = Package.EnvDte.Solution.FindProjectItem(file);
                        if (prjitem != null)
                        {
                            if (prjitem.Document != null)
                            {
                                prjitem.Document.Close();
                            }
                            var writer = new ResXResourceWriter(file);
                            foreach (var itemdg in DGResx.Items)
                            {
                                var item = itemdg as ModelResxTranslateAll;
                                if (item == null)
                                {
                                    continue;
                                }
                                var itemtype = item.GetType();
                                if (lng.Key == keyneutral)
                                {
                                    if (item.IsValidString)
                                    {
                                        var valuekey = itemtype.GetProperty("SourceValue").GetValue(item, null);
                                        var node = new ResXDataNode(item.Key, valuekey);
                                        var cmt = itemtype.GetProperty("Comment").GetValue(item, null) ?? string.Empty;
                                        if (!string.IsNullOrEmpty(cmt.ToString()))
                                        {
                                            node.Comment = cmt.ToString();
                                        }
                                        writer.AddResource(node);
                                    }
                                    else
                                    {
                                        var keyori = itemtype.GetProperty("OriginalValue").GetValue(item, null) ?? string.Empty;
                                        var resXDataNode = keyori as ResXDataNode;
                                        if (resXDataNode != null)
                                        {
                                            writer.AddResource(resXDataNode);
                                        }
                                    }
                                    continue;
                                }
                                var editfield = "Value_" + lng.Key.Replace("-", "_");
                                var origfield = "Original_" + lng.Key.Replace("-", "_");
                                var valueedt = itemtype.GetProperty(editfield).GetValue(item, null) ?? string.Empty;
                                var valueori = itemtype.GetProperty(origfield).GetValue(item, null) ?? string.Empty;
                                var isvalid = true;
                                // ReSharper disable PossibleInvalidOperationException
                                if (ChkSync.IsChecked.Value)
                                // ReSharper restore PossibleInvalidOperationException
                                {
                                    isvalid = !item.KeyOrphans;
                                }
                                if (isvalid)
                                {
                                    if (item.IsValidString)
                                    {
                                        if (!string.IsNullOrEmpty(valueedt.ToString()))
                                        {
                                            var node = new ResXDataNode(item.Key, valueedt);
                                            writer.AddResource(node);
                                        }
                                        if (!valueori.Equals(valueedt))
                                        {
                                            itemtype.GetProperty(origfield).SetValue(item, valueedt, null);
                                        }
                                    }
                                    else
                                    {
                                        var resXDataNode = valueori as ResXDataNode;
                                        if (resXDataNode != null)
                                        {
                                            writer.AddResource(resXDataNode);
                                        }
                                    }
                                }
                            }
                            writer.Generate();
                            writer.Close();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Cursor = cur;
                MessageBox.Show(ex.Message, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Error);
            }
            // ReSharper disable PossibleNullReferenceException
            var defres = _rootProject + (string)CboFilesResx.SelectedItem;
            // ReSharper restore PossibleNullReferenceException
            var fi = new FileInfo(defres);
            CreateResxCollection(fi.FullName, cur);
            Cursor = cur;
            IsEnabled = true;
        }

        private void DgResxMouseMove(object sender, MouseEventArgs e)
        {
            var dep = (DependencyObject)e.OriginalSource;

            // iteratively traverse the visual tree
            while ((dep != null) && !(dep is DataGridCell) && !(dep is DataGridColumnHeader))
            {
                dep = VisualTreeHelper.GetParent(dep);
            }

            if (dep == null)
                return;

            //if (dep is DataGridColumnHeader)
            //{
            //    var columnHeader = dep as DataGridColumnHeader;
            //    // do something
            //}

            if (dep is DataGridCell)
            {
                var cell = dep as DataGridCell;
                if (cell.ToolTip != null)
                {
                    return;
                }

                if (cell.Column.DisplayIndex <= 2)
                {
                    while ((dep != null) && !(dep is DataGridRow))
                    {
                        dep = VisualTreeHelper.GetParent(dep);
                    }
                    if (dep != null)
                    {
                        var row = dep as DataGridRow;
                        var item = row.Item as ModelResxTranslateAll;
                        if (item != null)
                        {
                            if (!string.IsNullOrEmpty(item.Comment))
                            {
                                var text = new TextBlock { Text = item.Comment, TextWrapping = TextWrapping.Wrap, Width = 150 };
                                cell.ToolTip = text;
                            }
                        }
                    }
                }
            }
        }

        private void DgResxInitializingNewItem(object sender, InitializingNewItemEventArgs e)
        {
            var item = (ModelResxTranslateAll)e.NewItem;
            item.IsValidString = true;
            item.KeyOrphans = false;
            item.Key = _newKeyResx;
            item.Comment = _newCommentResx;
            _newKeyResx = null;
            _newCommentResx = null;
            _qtdTargetNOk += _headerLngs.Count;
            PrgbarTrans.Maximum += _headerLngs.Count;
            QtdTotrans.Text = _qtdTargetNOk.ToString(CultureInfo.InvariantCulture);
        }

        private void PreviewCommandHandler(object sender, ExecutedRoutedEventArgs e)
        {
            if (e.Command == DataGrid.DeleteCommand)
            {
                var result = MessageBox.Show(AppRes.QDeletekey, AppRes.ToolWindowTitle, MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result == MessageBoxResult.No)
                {
                    e.Handled = true;
                }
                else
                {
                    var item = DGResx.SelectedItem as ModelResxTranslateAll;
                    if (item != null)
                    {
                        if (!item.IsValidString)
                        {
                            return;
                        }
                        if (item.KeyOrphans)
                        {
                            _qtdKeyOrph--;
                        }
                        else
                        {
                            foreach (var keypair in _headerLngs)
                            {
                                var edtfield = "Value_" + keypair.Key.Replace("-", "_");
                                var editvalue = item.GetType().GetProperty(edtfield).GetValue(item, null) ?? string.Empty;
                                if (string.IsNullOrEmpty(editvalue.ToString()))
                                {
                                    _qtdTargetNOk--;
                                }
                            }
                        }
                        PrgbarTrans.Maximum -= _headerLngs.Count;
                        QtdTotrans.Text = _qtdTargetNOk.ToString(CultureInfo.InvariantCulture);
                        QtdOrph.Text = _qtdKeyOrph.ToString(CultureInfo.InvariantCulture);
                    }
                }
            }
            else
            {
                var cmd = e.Command as RoutedCommand;
                if (cmd != null)
                {
                    if (cmd.Name == "BeginEdit")
                    {
                        var item = DGResx.SelectedItem;
                        if (item.ToString() == "{NewItemPlaceholder}")
                        {
                            {
                                var dialog = new NewKeyResourceDialog { Items = DGResx.Items };
                                dialog.ShowModal();
                                if (string.IsNullOrEmpty(dialog.Key) || string.IsNullOrEmpty(dialog.Value))
                                {
                                    e.Handled = true;
                                }
                                else
                                {
                                    _newKeyResx = dialog.Key;
                                    _newCommentResx = dialog.Comment;
                                }
                            }
                        }
                    }
                }
            }
        }

        private void ChangeEngineMouseEnter(object sender, MouseEventArgs e)
        {
            ChangeEngine.Source = new BitmapImage(new Uri(Constants.RootResource + Constants.RotateOn, UriKind.RelativeOrAbsolute));
        }

        private void ChangeEngineMouseLeave(object sender, MouseEventArgs e)
        {
            ChangeEngine.Source = new BitmapImage(new Uri(Constants.RootResource + Constants.RotateOff, UriKind.RelativeOrAbsolute));
        }

        private void ChangeEngineMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            switch (UserSettings.Current.EngineTranslate)
            {
                case EngineTranslate.Bing:
                    {
                        Engine.Source = new BitmapImage(new Uri(Constants.RootResource + Constants.GoogleLogo, UriKind.RelativeOrAbsolute));
                        UserSettings.Current.EngineTranslate = EngineTranslate.Google;
                    }
                    break;
                case EngineTranslate.Google:
                    {
                        Engine.Source = new BitmapImage(new Uri(Constants.RootResource + Constants.BingLogo, UriKind.RelativeOrAbsolute));
                        UserSettings.Current.EngineTranslate = EngineTranslate.Bing;
                    }
                    break;
            }
            UserSettings.Save();
        }

    }
}

